<template>
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="账号" prop="username">
            <el-input :prefix-icon="User" v-model="form.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input :prefix-icon="Lock" v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item class="btns">
            <el-button type="primary" @click="onSubmit(ruleFormRef)">登录</el-button>
            <el-button type="danger" @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue'
import { useRouter } from "vue-router"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { User,Lock} from '@element-plus/icons-vue'
import useUserStore from "@/store/modules/user";
const useStore = useUserStore();
const router = useRouter()

const form = reactive({
    username: '',
    password: ''
})
const ruleFormRef = ref<FormInstance>()
// 验证限制
const rules = reactive<FormRules>({
    username: [
        {
            required: true,
            message: "请输入账号",
            trigger: ["blur", "change"]
        }
    ],
    password: [
        {
            required: true,
            message: "请输入密码",
            trigger: ["blur", "change"]
        }
    ]
})
// 提交登录
const onSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            try {
                const message = await useStore.userLogin(form)
                ElMessage.success(message)
                router.push("/")
            } catch (error: any) {
                ElMessage.error(error.message)
            }
        } else {
            ElMessage.warning("请正确填写表单");
        }
    })
}
// 重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style scoped lang="scss">
.el-form-item{
    margin: 2rem 0;
}
.btns {
    :deep(.el-form-item__content) {
        display: flex;
        justify-content: center;
    }
}
</style>
